package com.tledu.springboot04.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tledu.springboot04.domain.Address;
import com.tledu.springboot04.service.IBaseService;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.lang.reflect.Field;
import java.util.List;

@NoArgsConstructor
@AllArgsConstructor
public class BaseServiceImpl<T, E extends BaseMapper<T>> implements IBaseService<T> {
    /**
     * 当前类、子类、同一个包下
     */
    protected E mapper;



    @Override
    public void insert(T entity) {
        mapper.insert(entity);
    }

    @Override
    public void update(T entity) {
        mapper.updateById(entity);
    }

    @Override
    public void delete(Integer id) {
        mapper.deleteById(id);
    }

    @Override
    public T selectById(Integer id) {
        return mapper.selectById(id);
    }

    @Override
    public List<T> list(T condition) {
        QueryWrapper<T> wrapper= new QueryWrapper<>();
        // 希望有查询条件
        Class clazz = condition.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                if (field.get(condition) == null) {
                    continue;
                }
                // 说明我们传递过来这个数据，需要根据这个数据进行查询
                // 获取查询的列
                TableField tableField = field.getAnnotation(TableField.class);
                if (tableField == null) {
                    wrapper.eq(field.getName(), field.get(condition));
                }else {
                    wrapper.eq(tableField.value(), field.get(condition));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return mapper.selectList(wrapper);
    }
}
